#import "ALScrollFixedElementAnimation.h"


@implementation ALScrollFixedElementAnimation

@synthesize scrollStartX;
@synthesize scrollEndX;
@synthesize scrollView;
@synthesize subviewStartRect;
@synthesize subviewEndRect;
@synthesize subview;

-(void)animateScrollView:(NSScrollView *)aScrollView toX:(CGFloat)endX {
	[self setScrollView:aScrollView];
	CGFloat startX = [aScrollView documentVisibleRect].origin.x;
	[self setScrollStartX:startX];
	[self setScrollEndX:endX];
}

-(void)animateScrollView:(NSScrollView *)aScrollView toRect:(NSRect)aRect {
	[self setScrollView:aScrollView];
	NSRect visibleRect = [aScrollView documentVisibleRect];
	CGFloat startX = visibleRect.origin.x;
	[self setScrollStartX:startX];
	if (startX < aRect.origin.x)
		[self setScrollEndX:NSMaxX(aRect) - visibleRect.size.width];
	else 
		[self setScrollEndX:aRect.origin.x];
}

-(void)animateSubview:(NSView *)aView fromRect:(NSRect)startRect toRect:(NSRect)endRect {
	[self setSubview:aView];
	[self setSubviewStartRect:startRect];
	[self setSubviewEndRect:endRect];
}

-(void)updateScrollView:(NSAnimationProgress)progress {
	CGFloat start = [self scrollStartX];
	CGFloat end = [self scrollEndX];
	if (![self scrollView] || start == end)
		return;
	CGFloat currentX = ((end - start) * progress) + start;
	[[[self scrollView] documentView] scrollPoint:NSMakePoint(currentX, 0)];
}

-(void)updateSubview:(NSAnimationProgress)progress {
	NSRect start = [self subviewStartRect];
	NSRect end = [self subviewEndRect];
	if (![self subview] || NSEqualRects(start, end))
		return;
	CGFloat x = ((end.origin.x - start.origin.x) * progress) + start.origin.x;
	CGFloat y = ((end.origin.y - start.origin.y) * progress) + start.origin.y;
	CGFloat width = ((end.size.width - start.size.width) * progress) + start.size.width;
	CGFloat height = ((end.size.height - start.size.height) * progress) + start.size.height;
	NSRect subviewFrame = NSMakeRect(x, y, width, height);
	[[self subview] setFrame:subviewFrame];
}

-(void)setCurrentProgress:(NSAnimationProgress)progress {
	[super setCurrentProgress:progress];
	[self updateScrollView:progress];
	[self updateSubview:progress];
}

@end
